package com.ainote.service.impl;



import com.ainote.service.SummaryService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

@Service
public class SummaryServiceImpl implements SummaryService {

    @Value("${nlp.provider:deepseek}")
    private String provider;

    @Value("${nlp.deepseek.api_key:}")
    private String deepseekKey;

    @Value("${nlp.chatglm.api_key:}")
    private String chatglmKey;

    @Value("${nlp.spark.api_key:}")
    private String sparkKey;

    private final OkHttpClient http = new OkHttpClient();
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public String summarize(String text) throws Exception {
        return switch (provider.toLowerCase()) {
            case "chatglm" -> summarizeWithChatGLM(text);
            case "spark" -> summarizeWithSpark(text);
            default -> summarizeWithDeepSeek(text);
        };
    }

    // DeepSeek API
    private String summarizeWithDeepSeek(String text) throws IOException {
        String api = "https://api.deepseek.com/v1/chat/completions";
        String prompt = "请阅读以下会议记录，提取会议摘要、主要议题、关键决策和待办事项：\n\n" + text;

        Map<String, Object> body = Map.of(
                "model", "deepseek-chat",
                "messages", new Object[]{
                        Map.of("role", "system", "content", "你是一位专业会议纪要生成助手。"),
                        Map.of("role", "user", "content", prompt)
                }
        );

        Request req = new Request.Builder()
                .url(api)
                .addHeader("Authorization", "Bearer " + deepseekKey)
                .post(RequestBody.create(mapper.writeValueAsString(body),
                        MediaType.parse("application/json")))
                .build();

        try (Response resp = http.newCall(req).execute()) {
            String json = resp.body().string();
            JsonNode root = mapper.readTree(json);
            return root.path("choices").get(0).path("message").path("content").asText();
        }
    }

    // ChatGLM（智谱AI）
    private String summarizeWithChatGLM(String text) throws IOException {
        String api = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
        String prompt = "根据以下会议内容生成简洁会议纪要和待办事项：\n\n" + text;

        Map<String, Object> body = Map.of(
                "model", "glm-4",
                "messages", new Object[]{
                        Map.of("role", "user", "content", prompt)
                }
        );

        Request req = new Request.Builder()
                .url(api)
                .addHeader("Authorization", "Bearer " + chatglmKey)
                .post(RequestBody.create(mapper.writeValueAsString(body),
                        MediaType.parse("application/json")))
                .build();

        try (Response resp = http.newCall(req).execute()) {
            String json = resp.body().string();
            JsonNode root = mapper.readTree(json);
            return root.path("choices").get(0).path("message").path("content").asText();
        }
    }

    // 讯飞星火（Spark）
    private String summarizeWithSpark(String text) throws IOException {
        String api = "https://spark-api.xf-yun.com/v1/chat/completions";
        String prompt = "请帮我总结以下会议的核心要点、决策和行动计划：\n\n" + text;

        Map<String, Object> body = Map.of(
                "model", "spark-3.5",
                "messages", new Object[]{
                        Map.of("role", "user", "content", prompt)
                }
        );

        Request req = new Request.Builder()
                .url(api)
                .addHeader("Authorization", "Bearer " + sparkKey)
                .post(RequestBody.create(mapper.writeValueAsString(body),
                        MediaType.parse("application/json")))
                .build();

        try (Response resp = http.newCall(req).execute()) {
            String json = resp.body().string();
            JsonNode root = mapper.readTree(json);
            return root.path("choices").get(0).path("message").path("content").asText();
        }
    }
}
